package com.xymtop.Interceptor;

import com.xymtop.Ann.Router;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 计数器过滤器
 *
 * @author pan_junbiao
 *
 */
public class ApplicationFilter implements Filter
{
    private Router router = new Router();
    // 初始化方法
    @Override
    public void init(FilterConfig filterConfig) throws ServletException
    {

    }

    // 过滤处理方法
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException
    {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
//        设置跨域请求
        Cors(res);
//        调用路由
        router.getRouter(req,res);

//        传递
        chain.doFilter(request,response);
    }

    // 销毁方法
    @Override
    public void destroy()
    {
        // 释放资源

    }

    private  void Cors(HttpServletResponse response){

        //允许跨域主机地址
        response.setHeader("Access-Control-Allow-Origin", "*");
        //允许跨域方法
        response.setHeader("Access-Control-Allow-Methods", "*");
        //缓存时间
        response.setHeader("Access-Control-Max-Age", "3600");
        //允许跨域的请求头
        response.setHeader("Access-Control-Allow-Headers", "*");
        //是否携带cookie
        response.setHeader("Access-Control-Allow-Credentials", "true");
    }

}